package com.banmoon.wait;

import cn.hutool.core.date.DateUtil;

public class Demo3 {

    public static void main(String[] args) {
        Demo3Flag flag = new Demo3Flag();
        new Thread(new Demo3Producer(flag)).start();
        new Thread(new Demo3Consumer(flag)).start();
    }
}

class Demo3Producer implements Runnable{

    private Demo3Flag flag;

    public Demo3Producer(Demo3Flag flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            flag.production();
        }
    }
}

class Demo3Consumer implements Runnable{

    private Demo3Flag flag;

    public Demo3Consumer(Demo3Flag flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            flag.consumption();
        }
    }
}

class Demo3Flag{

    // 标志位 true：生成，false：消费
    private boolean flag;

    public Demo3Flag() {
        this.flag = true;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public synchronized void production(){
        if(!this.flag){
            try {
                wait();
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "：正在生产..." + DateUtil.now());
        // 生产完成，标志位设置为可以消费
        this.flag = false;
        notifyAll();
    }

    public synchronized void consumption(){
        if(this.flag){
            try {
                wait();
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "：正在消费..." + DateUtil.now());
        // 消费完成，标志位设置为可以继续生产
        this.flag = true;
        notifyAll();
    }
}